import paramiko
import socket


def check_remote_host(hostname, port=22, username='root', password=None, key_path=None):
    result = {'hostname': hostname, 'python': False, 'psutil': False, 'error': None}

    try:
        # 创建SSH客户端
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 认证连接（支持密码或密钥）
        if key_path:
            private_key = paramiko.RSAKey.from_private_key_file(key_path)
            client.connect(hostname, port, username=username, pkey=private_key)
        else:
            client.connect(hostname, port, username=username, password=password)

        # 检查Python是否存在
        stdin, stdout, stderr = client.exec_command("python3 --version || python --version", timeout=5)
        exit_code = stdout.channel.recv_exit_status()
        if exit_code == 0:
            result['python'] = True
        else:
            result['error'] = stderr.read().decode().strip()
            return result

        # 检查psutil库是否存在
        stdin, stdout, stderr = client.exec_command("python3 -c 'import psutil' 2>&1", timeout=5)
        exit_code = stdout.channel.recv_exit_status()
        result['psutil'] = (exit_code == 0)
        if exit_code != 0:
            result['error'] = stderr.read().decode().strip()

        client.close()
    except paramiko.AuthenticationException:
        result['error'] = "认证失败"
    except socket.timeout:
        result['error'] = "连接超时"
    except Exception as e:
        result['error'] = str(e)

    return result


def generate_report(results):
    print("巡检报告：")
    print("{:<20} {:<10} {:<10} {:<20}".format("主机名", "Python", "psutil", "错误信息"))
    for res in results:
        print("{:<20} {:<10} {:<10} {:<20}".format(
            res['hostname'],
            "是" if res['python'] else "否",
            "是" if res['psutil'] else "否",
            res['error'] or "无"
        ))


if __name__ == "__main__":
    # 配置主机列表（示例）
    hosts = [
        {'hostname': '172.16.100.70', 'username': 'root', 'password': 'shsnc!@#'},
        {'hostname': '172.16.100.200', 'username': 'root', 'password': 'shsnc!@#'},
    ]

    results = []
    for host in hosts:
        # 调用检查函数
        result = check_remote_host(
            hostname=host['hostname'],
            username=host.get('username', 'root'),
            password=host.get('password'),
            key_path=host.get('key_path')
        )
        results.append(result)

    # 生成报告
    generate_report(results)